const { contextBridge, ipcRenderer } = require("electron");
contextBridge.exposeInMainWorld("electronAPI", {
  showSaveDialog: (options) => ipcRenderer.invoke("show-save-dialog", options),
  showOpenDialog: (options) => ipcRenderer.invoke("show-open-dialog", options),
  downloadVideo: (options) => {
    console.log('预加载脚本收到下载请求:', options);
    return ipcRenderer.invoke('download-video', options);
  },
  openFileDialog: async (options) => {
    return ipcRenderer.invoke('dialog:openFile', options);
  },
// 带进度的文件下载
  downloadFileWithProgress: async (options, progressCallback) => {
    return new Promise((resolve, reject) => {
      const progressHandler = (event, progress) => {
        progressCallback(progress);
      };

      ipcRenderer.on('downloadProgress', progressHandler);

      ipcRenderer.invoke('downloadFileWithProgress', options)
          .then(resolve)
          .catch(reject)
          .finally(() => {
            ipcRenderer.removeListener('downloadProgress', progressHandler);
          });
    });
  },
  // 读取文件二进制内容（通过主进程间接读取）
  readFileAsArrayBuffer: async (filePath) => {
    return ipcRenderer.invoke('file:readBinary', filePath);
  },
  uploadVideoFile: (params) => ipcRenderer.invoke('upload-video-file', params),
  // 如需分块传输，还需暴露进度监听（可选）
  onUploadProgress: (callback) => ipcRenderer.on('upload-progress', (_, progress) => callback(progress)),
  executeCommand: (command, args) =>
    ipcRenderer.invoke("execute-command", command, args),

  // 视频采集 API
  startVideoCollection: (options) =>
    ipcRenderer.invoke("start-video-collection", options),
  stopVideoCollection: () => ipcRenderer.invoke("stop-video-collection"),
  finalizeCollection: (options) =>
    ipcRenderer.invoke("finalize-collection", options),
  checkFFmpeg: () => ipcRenderer.invoke("check-ffmpeg"),
  requestSavePath: (defaultFileName) => ipcRenderer.invoke('request-save-path', defaultFileName),
  downloadFile: (params) => ipcRenderer.invoke('download-file', params),
  // 保存遥测数据API
  saveTelemetryData: (options) =>
    ipcRenderer.invoke("save-telemetry-data", options),

  // 删除文件API
  deleteFile: (filePath) =>
    ipcRenderer.invoke("delete-file", filePath),

  // 导出采集数据API（包含视频和遥测文件）
  exportCollectionData: (options) =>
    ipcRenderer.invoke("export-collection-data", options),

  // 批量导出采集数据API
  batchExportData: (options) =>
    ipcRenderer.invoke("batch-export-data", options),

  // 获取采集文件API
  getCollectionFiles: (options) =>
    ipcRenderer.invoke("get-collection-files", options),

  // 读取遥测文件API
  readTelemetryFile: (options) =>
    ipcRenderer.invoke("read-telemetry-file", options),

  // RTSP服务器控制API
  startRTSPServer: () => ipcRenderer.invoke("start-rtsp-server"),
  stopRTSPServer: () => ipcRenderer.invoke("stop-rtsp-server"),
  getRTSPServerStatus: () => ipcRenderer.invoke("get-rtsp-server-status"),
  // UDP 相关方法
// UDP 相关方法
  onUdpData: (callback) => {
    ipcRenderer.on('udp-data', callback);
  },
// 开始监听 UDP 数据
  startUdpListener: (address, port,selectedTaskId,allParam,confirmedSelectedParam,telemetryDataSaveFileFolder) => {
    return ipcRenderer.invoke('start-udp-listener', { address, port,selectedTaskId,allParam,confirmedSelectedParam,telemetryDataSaveFileFolder });
  },
// 停止监听 UDP
  stopUdpListener: () => {
    return ipcRenderer.invoke('stop-udp-listener');
  },
  
  // TCP 相关方法
  // 连接相关
  tcpConnect: (config) => ipcRenderer.invoke('tcp-connect', config),
  tcpDisconnect: () => ipcRenderer.invoke('tcp-disconnect'),

  // 发送请求
  tcpDownloadConfig: (payload) => ipcRenderer.invoke('tcp-config-download', payload),

  // 监听连接状态变化
  tcpOnStatusChange: (callback) => ipcRenderer.on('tcp-status-change', (_event, status) => callback(status)),
  tcpOffStatusChange: () => ipcRenderer.removeAllListeners('tcp-status-change'),

  // 监听日志输出
  tcpOnLog: (callback) => ipcRenderer.on('tcp-log', (_event, msg) => callback(msg)),
  tcpOffLog: () => ipcRenderer.removeAllListeners('tcp-log'),
// 移除监听器
  removeAllListeners: (channel) => {
    ipcRenderer.removeAllListeners(channel);
  },
  
  // 获取任务文件列表
  getFilesFromDirectory: () => ipcRenderer.invoke('get-files-from-directory')
});
